#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
from jinja2 import Template
import shutil
import socket

def get_host_ip():
    try:
        # Create a new socket using the given address family,
        # socket type and protocol number.
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Connect to a remote socket at address.
        # (The format of address depends on the address family.)
        address = ("8.8.8.8", 80)
        s.connect(address)

        # Return the socket’s own address.
        # This is useful to find out the port number of an IPv4/v6 socket, for instance.
        # (The format of the address returned depends on the address family.)
        sockname = s.getsockname()
        # print(sockname)

        ip = sockname[0]
        port = sockname[1]
    finally:
        s.close()

    return ip

import colorama
from colorama import Fore
from colorama import Style

colorama.init()


IP = get_host_ip()

ROOT=os.path.abspath(os.path.dirname(__file__))

#模板文件的路径
TPL_PATH=os.path.join(ROOT,"cluster-conf.j2")

COMPOSE_TPL_PATH=os.path.join(ROOT,"docker-compose.j2")

TPL_CONTENT=""
# 读取模板文件的内容
with open(TPL_PATH, 'rt') as f:
    TPL_CONTENT = f.read()

COMPOSE_TPL_CONTENT=""
# 读取模板文件的内容
with open(COMPOSE_TPL_PATH, 'rt') as f:
    COMPOSE_TPL_CONTENT = f.read()

#####################################################################
#开始的端口
start_port=6381

#结束端口
end_port=6386

#密码
password="123456"

#####################################################################


# 判断cluster 目录是否存在
REDIS_CLUSTER_CNF=os.path.join(ROOT,"redis_cluster_cnf")

if os.path.exists(REDIS_CLUSTER_CNF):
    shutil.rmtree(REDIS_CLUSTER_CNF)
    pass


services=[]
ports=[]

# 循环所有端口生成配置文件
for port in range(start_port,end_port+1):
    ports.append(port)
    t = Template(TPL_CONTENT)
    s=t.render(password=password,port=port,ip=IP)
    # 检查端口目录是不是已经存在了

    port_path = os.path.join(REDIS_CLUSTER_CNF,"{}".format(port))
    if os.path.exists(port_path):
        shutil.rmtree(port_path)
        pass

    conf_path = os.path.join(port_path,"conf")
    data_path = os.path.join(port_path,"data")

    os.makedirs(conf_path, exist_ok=True)
    os.makedirs(data_path, exist_ok=True)

    # 写入配置文件
    with open(os.path.join(conf_path,"redis.conf"), 'wt') as f:
        f.write(s)
        pass


    services.append({"port":port,"conf":conf_path,"data":data_path})
    pass

# 写入配置文件
with open(os.path.join(REDIS_CLUSTER_CNF,"docker-compose.yml"), 'wt') as f:
    t = Template(COMPOSE_TPL_CONTENT)
    s=t.render(services=services)
    f.write(s)
    pass



colorama.init()
print(Fore.GREEN  +"1) 命令行执行下面的命令，启动docker-compose"+ Style.RESET_ALL)
print(Fore.YELLOW +"cd {0} && docker-compose up -d".format(REDIS_CLUSTER_CNF))

fmt="""
    redis-cli -a {{password}} --cluster create {% for port in ports %} {{ip}}:{{port}} {%endfor%} --cluster-replicas 1
"""
t=Template(fmt)
s=t.render(password=password,ip=IP,ports=ports)
print(" "*80)
print(Fore.GREEN +"2) 命令行执行下面的命令，配置redis cluster集群"+ Style.RESET_ALL)
print(Fore.YELLOW +s)




